﻿using LibNiconico.NiconicoApi.Internal.Http;
using LibNiconico.NiconicoApi.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace LibNiconico.NiconicoApi.Internal
{
    /// <summary>
    /// JSON形式で取得するニコニコ情報取得API
    /// </summary>
    internal class NiconicoInfoGetApiJsonImpl: NiconicoInfoGetApiImpl

    {
        internal NiconicoInfoGetApiJsonImpl(Uri url, INiconicoHttpClient api) : base(url, api) { }

        /// <summary>
        /// 非同期にGetメソッドで情報を取得
        /// </summary>
        /// <param name="urlAble"></param>
        /// <returns></returns>
        internal protected async Task<NiconicoHttpResponse<JObject>> GetAsync(NicoUrlAble urlAble)
        {
            var response = await GetStreamAsync(urlAble).ConfigureAwait(false);
            return NiconicoHttpResponse.ConvertContent( parse(response.Content),response);
        }

        /// <summary>
        /// 非同期にPostメソッドで情報を取得
        /// </summary>
        /// <param name="postAble"></param>
        /// <returns></returns>
        internal protected async Task<NiconicoHttpResponse<JObject>> PostAsync(NicoUrlEncodedPostAble postAble)
        {
            var response = await PostStreamAsyunc(postAble).ConfigureAwait(false);
            return NiconicoHttpResponse.ConvertContent(parse(response.Content),response);
        }

        private static JObject parse(Stream jsonText)
        {

            
            using(StreamReader streamReader = new StreamReader ( jsonText))
            {
                using(JsonTextReader jsonReader = new JsonTextReader(streamReader))
                {
                    return (JObject)JToken.ReadFrom(jsonReader);
                }

            }
            
        }
    }
}
